﻿// Copyright (c) Inossem. All rights reserved.
// Licensed under the LGPL-3.0 license. See LICENSE file in the project root for full license information.
using DWF.Studio.Custom;
using DWF.Studio.Host;
using DWF.Studio.ISerivces;
using DWF.Studio.Models;
using DWF.Studio.Plugin;
using DWF.Studio.Plugin.Contract;
using DWF.Studio.Project;
using DWF.Studio.Services;
using DWF.Studio.Share.Log;
using DWF.Studio.Share.Utils;
using Microsoft.Win32;
using Ookii.Dialogs.Wpf;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using VeryHotKeys.Wpf;
using WpfMessageBoxLibrary;

namespace DWF.Studio.Views
{
    /// <summary>
    /// 主窗体
    /// </summary>
    public partial class MainWindow : Window
    {
        /// <summary>
        /// 主区域
        /// </summary>
        private PageMainRegion _pageMainRegion = null;

        /// <summary>
        /// 起始界面
        /// </summary>
        private PageStart _pageStart = null;

        /// <summary>
        /// 插件管理器
        /// </summary>
        private PluginManager _pluginManager = null;

        /// <summary>
        /// 工程记录服务
        /// </summary>
        private IProjectRecordsService _projectRecordsService = null;

        private IAppService _appService = null;

        /// <summary>
        /// 是否打开工程
        /// </summary>
        private bool _isOpenedProject = false;

        /// <summary>
        /// 是否打开对话框窗体
        /// </summary>
        private bool _isOpenedWinDialoag = false;

        /// <summary>
        /// 设置信息服务
        /// </summary>
        private IConfigService _configService = null;

        private IExecutionService _executionService = null;

        private ISysUpgradeService _sysUpgradeService = null;

        private SysVersionInfo _lastestVersion = null;

        public MainWindow()
        {
            InitializeComponent();

            if (!DesignerProperties.GetIsInDesignMode(this))
            {
                init();
            }
        }

        /// <summary>
        /// 初始化
        /// </summary>
        private void init()
        {
            this._pageMainRegion = new PageMainRegion();
            this._pageStart = new PageStart();
            this.frameMain.Content = this._pageStart;
            this._pluginManager = PluginManager.Instance;
            this._projectRecordsService = new ProjectRecordsService();
            this._configService = new ConfigService();
            this._executionService = ExecutionService.Instance;
            this._appService = AppService.Instance;
            this._sysUpgradeService = new SysUpgradeService(_appService);

            GlobalActionHandler.ProjectOpened += openedProject;
            GlobalActionHandler.ProjectClosing += closeProject;
            GlobalActionHandler.SetStatusBarMsg += setStatusBarMsg;
            GlobalActionHandler.RefreshTitleName += refreshTitleName;
            GlobalActionHandler.ProjectRecordsRefresh += (e) => { refreshMenuRecentProjects(); };

            GlobalActionHandler.BackStartPage += backStartPage;

            CustomCommands.CmdNewProjectSequence.InputGestures.Add(new KeyGesture(Key.Q, ModifierKeys.Control | ModifierKeys.Shift));
            CustomCommands.CmdNewProjectFlowchart.InputGestures.Add(new KeyGesture(Key.F, ModifierKeys.Control | ModifierKeys.Shift));
            CustomCommands.CmdOpenProject.InputGestures.Add(new KeyGesture(Key.O, ModifierKeys.Control));

            CustomCommands.CmdScriptSave.InputGestures.Add(new KeyGesture(Key.S, ModifierKeys.Control));
            CustomCommands.CmdAllScriptSave.InputGestures.Add(new KeyGesture(Key.S, ModifierKeys.Control | ModifierKeys.Shift));

            CustomCommands.CmdScriptRun.InputGestures.Add(new KeyGesture(Key.F5, ModifierKeys.Control));
            CustomCommands.CmdScriptStop.InputGestures.Add(new KeyGesture(Key.F5, ModifierKeys.Shift, LocalizationProvider.GetLocalizedString("WinMain_Menu_File_Stop_Shift_F5")));

            CustomCommands.CmdToggleBreakPoint.InputGestures.Add(new KeyGesture(Key.F9));
            CustomCommands.CmdScriptDebug.InputGestures.Add(new KeyGesture(Key.F7));
            CustomCommands.CmdScriptDebugByStep.InputGestures.Add(new KeyGesture(Key.F10));

            CustomCommands.CmdSwitchProjectPanel.InputGestures.Add(new KeyGesture(Key.F1, ModifierKeys.Control));
            CustomCommands.CmdSwitchActivityPanel.InputGestures.Add(new KeyGesture(Key.F2, ModifierKeys.Control));
            CustomCommands.CmdSwitchSnippetPanel.InputGestures.Add(new KeyGesture(Key.F3, ModifierKeys.Control));

            CustomCommands.CmdSwitchAttributePanel.InputGestures.Add(new KeyGesture(Key.R, ModifierKeys.Control));
            CustomCommands.CmdSwitchOutlinePanel.InputGestures.Add(new KeyGesture(Key.T, ModifierKeys.Control));

            CustomCommands.CmdLogPanel.InputGestures.Add(new KeyGesture(Key.D, ModifierKeys.Alt));

            CustomCommands.CmdNotesActivity.InputGestures.Add(new KeyGesture(Key.D, ModifierKeys.Control));
            CustomCommands.CmdCancelNotesActivity.InputGestures.Add(new KeyGesture(Key.P, ModifierKeys.Control));

            this.tbkCopyright.Text = AssemblyInfoHelper.AssemblyCopyright;


            initAutoSaveThread();
        }

        private async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            await this.loadPluginsAsync();
            CommandManager.InvalidateRequerySuggested();
        }

        #region 当前主窗体 Commands

        private void CanResizeWindow(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = ResizeMode == ResizeMode.CanResize || ResizeMode == ResizeMode.CanResizeWithGrip;
        }

        private void CanMinimizeWindow(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = ResizeMode != ResizeMode.NoResize;
        }

        private void CloseWindow(object sender, ExecutedRoutedEventArgs e)
        {
            this.Close();
        }

        private void MaximizeWindow(object sender, ExecutedRoutedEventArgs e)
        {
            SystemCommands.MaximizeWindow(this);
        }

        private void MinimizeWindow(object sender, ExecutedRoutedEventArgs e)
        {
            SystemCommands.MinimizeWindow(this);
        }

        private void RestoreWindow(object sender, ExecutedRoutedEventArgs e)
        {
            SystemCommands.RestoreWindow(this);
        }

        private void ShowSystemMenu(object sender, ExecutedRoutedEventArgs e)
        {
            var element = e.OriginalSource as FrameworkElement;
            if (element == null)
                return;

            var point = WindowState == WindowState.Maximized ? new Point(0, element.ActualHeight)
                : new Point(Left + BorderThickness.Left, element.ActualHeight + Top + BorderThickness.Top);
            point = element.TransformToAncestor(this).Transform(point);
            SystemCommands.ShowSystemMenu(this, point);

        }

        #endregion

        #region 初始化

        /// <summary>
        /// 初始化自动保存线程
        /// </summary>
        private void initAutoSaveThread()
        {
            #region
            var autoSaveThread = new Thread(new ThreadStart(() =>
            {
                while (true)
                {
                    var sysConfig = this._configService.LoadSysConfig();
                    if (sysConfig != null && sysConfig.IsAutoSave && !this.Dispatcher.HasShutdownStarted && !this.Dispatcher.HasShutdownFinished)
                    {
                        this.Dispatcher.Invoke(() =>
                        {
                            try
                            {
                                Custom.GlobalActionHandler.ScriptAutoSave?.Invoke(EventArgs.Empty);
                            }
                            catch (Exception ex)
                            {
                                LogHelper.Error(ex);
                            }
                        },
                        System.Windows.Threading.DispatcherPriority.Background);

                        Thread.Sleep(sysConfig.AutoSaveSpan.Value);
                    }
                    else
                    {
                        Thread.Sleep(TimeSpan.FromSeconds(30));
                    }
                }
            }));

            autoSaveThread.IsBackground = true;
            autoSaveThread.Priority = ThreadPriority.BelowNormal;
            autoSaveThread.Start();
            #endregion
        }

        /// <summary>
        /// 初始化插件
        /// </summary>
        private async Task loadPluginsAsync()
        {
            await this._pluginManager.LoadAsync();
            var plugins = this._pluginManager.Plugins;

            var tools = plugins.Where(item => item.PluginInfo.PluginType == Plugin.Contract.Enum.EPluginType.Tools);//工具
            var modules = plugins.Where(item => item.PluginInfo.PluginType == Plugin.Contract.Enum.EPluginType.Module);//模块

            var isContaintTools = tools.Any(item => true);
            if (isContaintTools)
            {
                toolBarPlugin.Visibility = Visibility.Visible;
                var menuTools = getMenuItem("menuTools");

                var groups = tools.GroupBy(item => item.PluginInfo.GroupName);
                foreach (var group in groups)
                {
                    menuTools.Items.Add(new Separator());
                    foreach (var tool in group)
                    {
                        try
                        {
                            await buildToolPluginAsync(tool, this.toolBarPlugin, menuTools);
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Error(ex);
                        }
                    }
                }
            }
            else
            {
                toolBarPlugin.Visibility = Visibility.Hidden;
            }
            if (await isUpgrade())
            {
                var msgProperties = new WpfMessageBoxProperties()
                {
                    Button = MessageBoxButton.YesNo,
                    ButtonYesText = LocalizationProvider.GetLocalizedString("MessageBox_Button_Yes"),
                    ButtonNoText = LocalizationProvider.GetLocalizedString("MessageBox_Button_No"),
                    Image = MessageBoxImage.Question,
                    Text = LocalizationProvider.GetLocalizedString("PageStart_MsgBox_Msg_IsUpgrade"),
                    Title = LocalizationProvider.GetLocalizedString("PageStart_MsgBox_Caption_Delete"),
                };

                Window owner = Window.GetWindow(this);
                MessageBoxResult dlgResult = WpfMessageBox.Show(owner, ref msgProperties);

                if (dlgResult == MessageBoxResult.Yes)
                {
                    WindowUpgrade windowUpgrade = new WindowUpgrade();
                    windowUpgrade.Owner = App.Current.MainWindow;
                    windowUpgrade.ShowDialog();
                }
            }
        }

        private async Task buildToolPluginAsync(PluginBase tool, ToolBar toolBar, MenuItem menuTools)
        {
            var cmdPlugin = new RoutedCommand("CmdPlugin", typeof(CustomCommands));
            CommandBinding bindingPlugin = new CommandBinding(cmdPlugin);
            bindingPlugin.CanExecute += IsExecuteForNotRun;
            bindingPlugin.PreviewCanExecute += IsExecuteForNotRun;
            bindingPlugin.Executed += (sender, e) =>
            {
                try
                {
                    tool.Excute();
                }
                catch (Exception ex)
                {
                    
                    throw new CustomException(ex.Message,ex);
                }
                
            };
            this.CommandBindings.Add(bindingPlugin);

            if (!String.IsNullOrWhiteSpace(tool.PluginInfo.StyleUri) && !String.IsNullOrWhiteSpace(tool.PluginInfo.StyleKey))
            {
                var btnTool = new System.Windows.Controls.Button();
                btnTool.Width = 40;
                btnTool.Height = 40;
                var resource = new ResourceDictionary
                {
                    Source = new Uri(tool.PluginInfo.StyleUri, UriKind.RelativeOrAbsolute)
                };
                btnTool.Style = ((Style)resource[tool.PluginInfo.StyleKey]);
                btnTool.ToolTip = await tool.GetLocalizedStringAsync(tool.PluginInfo.ToolTip);
                btnTool.Command = cmdPlugin;
                toolBar.Items.Add(btnTool);
            }
            else if (!String.IsNullOrWhiteSpace(tool.PluginInfo.Icon))
            {
                var btnTool = new System.Windows.Controls.Button();
                btnTool.Width = 40;
                btnTool.Height = 40;
                var resource = new ResourceDictionary
                {
                    Source = new Uri("/DWF.Studio;component/Themes/Generic.xaml", UriKind.RelativeOrAbsolute)
                };
                btnTool.Style = ((Style)resource["PluginButtonStyle"]);
                var icon = System.IO.Path.Combine(tool.PluginInfo.PluginDirectory, tool.PluginInfo.Icon);
                btnTool.Background = new ImageBrush(new BitmapImage(new Uri(icon)));
                btnTool.ToolTip = await tool.GetLocalizedStringAsync(tool.PluginInfo.ToolTip);
                btnTool.Command = cmdPlugin;
                toolBar.Items.Add(btnTool);
            }

            /*
             * 添加到菜单
             */
            var menuItem = new System.Windows.Controls.MenuItem();
            menuItem.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#000000"));
            menuItem.Header = await tool.GetLocalizedStringAsync(tool.PluginInfo.FriendlyName);
            menuItem.Command = cmdPlugin;

            menuTools.Items.Add(menuItem);
        }

        private void buildModulePlugin(PluginBase module, MenuItem menuModuls)
        {
            var menuItem = new System.Windows.Controls.MenuItem();
            menuItem.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#000000"));
            menuItem.Header = module.PluginInfo.FriendlyName;
            menuItem.Click += (sender, e) =>
            {
                module.Excute();
            };

            menuModuls.Items.Add(menuItem);
        }

        private MenuItem getMenuItem(string menuItemId)
        {
            var menuItem = this.Template.FindName(menuItemId, this) as MenuItem;
            return menuItem;
        }

        #endregion

        #region 事件处理

        /// <summary>
        /// 刷新菜单最近打开工程
        /// </summary>
        private void refreshMenuRecentProjects()
        {
            var projectRecords = _projectRecordsService.GetRecentRecords();
            var muItemRecentOpenProject = (MenuItem)this.GetTemplateChild("muItemRecentOpenProject");

            if (muItemRecentOpenProject != null)
            {
                muItemRecentOpenProject.Items.Clear();
                foreach (var projectRecord in projectRecords)
                {
                    var menuItem = new System.Windows.Controls.MenuItem();
                    menuItem.Header = projectRecord.ProjectName;
                    menuItem.CommandParameter = projectRecord;
                    menuItem.Command = CustomCommands.CmdOpenProjectRecord;
                    muItemRecentOpenProject.Items.Add(menuItem);
                }
            }
        }

        private void CmdOpenProjectRecord_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var projectRecord = e.Parameter as ProjectRecord;
           
            if (projectRecord != null)
            {
                var path = System.IO.Path.Combine(projectRecord.ProjectPath, StaticResource.ProjectFile);
                var oldPath = System.IO.Path.Combine(projectRecord.ProjectPath, StaticResource.OldProjectFile);

                if (FileHelper.CheckFileExisting(path))
                {
                    openProject(path);
                }
                else if (FileHelper.CheckFileExisting(oldPath))
                {
                    openProject(oldPath);
                }
                else
                {
                    var msgProperties = new WpfMessageBoxProperties()
                    {
                        Button = MessageBoxButton.YesNo,
                        ButtonYesText = LocalizationProvider.GetLocalizedString("MessageBox_Button_Yes"),
                        ButtonNoText = LocalizationProvider.GetLocalizedString("MessageBox_Button_No"),
                        Image = MessageBoxImage.Question,
                        Text = LocalizationProvider.GetLocalizedString("WinMain_MsgBox_Msg_ProjectFileNotExisting"),
                        Title = LocalizationProvider.GetLocalizedString("WinMain_MsgBox_Caption_ProjectFileNotExisting"),
                    };

                    MessageBoxResult dlgResult = WpfMessageBox.Show(this, ref msgProperties);
                    if (dlgResult == MessageBoxResult.Yes)
                    {
                        this._projectRecordsService.DelectRecord(projectRecord.ProjectPath);
                        GlobalActionHandler.ProjectRecordsRefresh?.Invoke(EventArgs.Empty);
                    }
                }
            }
        }
        /// <summary>
        /// 刷新工程名
        /// </summary>
        /// <param name="e"></param>
        private void refreshTitleName(TagEventArgs<string> e)
        {
            this.Title = StaticResource.WindowTitle + StaticResource.WindowTitleSeparator + e.Tag;
           
            GlobalActionHandler.ProjectRecordsRefresh?.Invoke(EventArgs.Empty);
        }
        /// <summary>
        /// 打开工程完成
        /// </summary>
        /// <param name="e"></param>
        private void openedProject(TagEventArgs<Project.ProjectInfo> e)
        {
            this.Title = StaticResource.WindowTitle + StaticResource.WindowTitleSeparator + e.Tag.DisplayName;
            this.frameMain.Content = this._pageMainRegion;
            _isOpenedProject = true;
            mainToolBar.Height = new GridLength(56);
            this._projectRecordsService.SetRecord(new Models.ProjectRecord() { ProjectId = e.Tag.Id, ProjectName = e.Tag.Name, ProjectPath = e.Tag.FullName, ModifyOn = DateTime.Now });

            GlobalActionHandler.ProjectRecordsRefresh?.Invoke(EventArgs.Empty);
        }

        /// <summary>
        /// 关闭工程
        /// </summary>
        /// <param name="e"></param>
        private void closeProject(EventArgs e)
        {
            this.Title = StaticResource.WindowTitle;
            this.frameMain.Content = this._pageStart;
            _isOpenedProject = false;
            mainToolBar.Height = new GridLength(0);
        }
        /// <summary>
        /// 回到startpage
        /// </summary>
        /// <param name="e"></param>
        private void backStartPage(TagEventArgs<bool> e)
        {
            if (e.Tag)
            {
                mainToolBar.Height = new GridLength(0);
                this.frameMain.Content = this._pageStart;
            }
            else
            {
                if (_isOpenedProject)
                {
                    mainToolBar.Height = new GridLength(56);
                    this.frameMain.Content = this._pageMainRegion;
                }
            }
        }
        /// <summary>
        /// 设置状态栏
        /// </summary>
        /// <param name="e"></param>
        private void setStatusBarMsg(TagEventArgs<string> e)
        {
            this.Dispatcher.InvokeAsync(() => this.txtblMsg.Text = e.Tag, System.Windows.Threading.DispatcherPriority.Normal);
        }

        #endregion

        #region 命令执行

        private void IsExecuteForNotRun(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = _executionService == null || _executionService.GetCurrentStatus() == ExecuteStatus.Idle;
            e.Handled = true;
        }

        private void IsExecuteForOpenProject(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = _isOpenedProject;
            e.Handled = true;
        }

        private void IsExecuteForOpenProjectAndNotRun(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = _isOpenedProject && (_executionService == null || _executionService.GetCurrentStatus() == ExecuteStatus.Idle);
            e.Handled = true;
        }

        private void IsExecuteCmdScriptRun(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = _isOpenedProject && (_executionService == null || _executionService.GetCurrentStatus() == ExecuteStatus.Idle);
            e.Handled = true;
        }

        private void IsExecuteCmdScriptStop(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = _isOpenedProject && (_executionService == null || _executionService.GetCurrentStatus() != ExecuteStatus.Idle);
            e.Handled = true;
        }

        private void IsExecuteCmdToggleBreakPoint(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = _isOpenedProject && (_executionService == null || _executionService.GetCurrentStatus() != ExecuteStatus.Executing);
            e.Handled = true;
        }

        private void IsExecuteCmdScriptDebug(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = _isOpenedProject && (_executionService == null || _executionService.GetCurrentStatus() != ExecuteStatus.Executing);
            e.Handled = true;
        }

        private void IsExecuteCmdScriptDebugByStep(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = _isOpenedProject && (_executionService == null || _executionService.GetCurrentStatus() != ExecuteStatus.Executing);
            e.Handled = true;
        }

        private void IsExecuteCmdValidateScript(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = _isOpenedProject && (_executionService == null || _executionService.GetCurrentStatus() == ExecuteStatus.Idle);
            e.Handled = true;
        }

        /// <summary>
        /// 新建Sequence工程 命令执行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmdNewProjectSequence_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if (!_isOpenedWinDialoag)
            {
                WindowCreateProject projectDialog = new WindowCreateProject();
                projectDialog.SetDefaultProjectName("Sequence");
                projectDialog.Owner = this;
                _isOpenedWinDialoag = true;
                var result = projectDialog.ShowDialog();
                var path = projectDialog.SelectedPath;
                var descri = projectDialog.Description;
                var platform = projectDialog.TargetPlatform;
                var wfLanguage = projectDialog.WorkflowLanguage;
                _isOpenedWinDialoag = false;

                if (result == true)
                {
                    if (!_isOpenedProject)
                    {
                        WindowLoading.ShowWindow(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_NewProject_Sequence"), this);//显示loading窗体
                        if (wfLanguage == StaticResource.WorkflowLanguage_vb)
                        {
                            GlobalActionHandler.ProjectCreate?.Invoke(new TagEventArgs<string, string, string, string, string>(path, descri, platform, wfLanguage, StaticResource.XamlFileTemplateSequence_vb));
                        }
                        else if (wfLanguage == StaticResource.WorkflowLanguage_cs)
                        {
                            GlobalActionHandler.ProjectCreate?.Invoke(new TagEventArgs<string, string, string, string, string>(path, descri, platform, wfLanguage, StaticResource.XamlFileTemplateSequence_cs));
                        }
                        WindowLoading.CloseWindow();//关闭loading窗体
                    }
                    else
                    {
                        var cea = new CancelEventArgs();
                        GlobalActionHandler.ProjectPreclose?.Invoke(cea);
                        if (cea.Cancel)
                        {
                            return;
                        }

                        WindowLoading.ShowWindow(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_CloseProject"), this);//显示loading窗体

                        GlobalActionHandler.ProjectClosing?.Invoke(EventArgs.Empty);
                        ProjectManager.Instance.UnloadProject();

                        WindowLoading.SetContent(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_CloseProject"));
                        var loaderHost = RemoteLoaderHost.GetCurrentInstance();
                        if (loaderHost != null)
                        {
                            loaderHost.Unload(); //卸载控件程序域
                        }

                        Task.Factory.StartNew(() =>
                        {
                            System.Threading.Thread.Sleep(1000);
                            Dispatcher.Invoke(() =>
                            {
                                WindowLoading.SetContent(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_NewProject_Sequence"));//显示loading窗体
                                try
                                {
                                    if (wfLanguage == StaticResource.WorkflowLanguage_vb)
                                    {
                                        GlobalActionHandler.ProjectCreate?.Invoke(new TagEventArgs<string, string, string, string, string>(path, descri, platform, wfLanguage, StaticResource.XamlFileTemplateSequence_vb));
                                    }
                                    else if (wfLanguage == StaticResource.WorkflowLanguage_cs)
                                    {
                                        GlobalActionHandler.ProjectCreate?.Invoke(new TagEventArgs<string, string, string, string, string>(path, descri, platform, wfLanguage, StaticResource.XamlFileTemplateSequence_cs));
                                    }
                                    WindowLoading.CloseWindow();//关闭loading窗体
                                }
                                catch (Exception ex)
                                {
                                    WindowLoading.CloseWindow();//关闭loading窗体
                                    LogHelper.Error(ex);
                                    var msgProperties = new WpfMessageBoxProperties()
                                    {
                                        Button = MessageBoxButton.OK,
                                        ButtonOkText = LocalizationProvider.GetLocalizedString("MessageBox_Button_OK"),
                                        Image = MessageBoxImage.Error,
                                        Text = LocalizationProvider.GetLocalizedString("App_MsgBox_Msg_Exception"),
                                        Title = LocalizationProvider.GetLocalizedString("App_MsgBox_Caption_Exception"),
                                    };
                                    WpfMessageBox.Show(this, ref msgProperties);
                                }
                            });
                        });
                    }
                }
            }
        }

        /// <summary>
        /// 新建Flowchart工程  命令执行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmdNewProjectFlowchart_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if (!_isOpenedWinDialoag)
            {
                WindowCreateProject projectDialog = new WindowCreateProject();
                projectDialog.SetDefaultProjectName("Flowchart");
                projectDialog.Owner = this;
                _isOpenedWinDialoag = true;
                var result = projectDialog.ShowDialog();
                var path = projectDialog.SelectedPath;
                var descri = projectDialog.Description;
                var platform = projectDialog.TargetPlatform;
                var wfLanguage = projectDialog.WorkflowLanguage;
                _isOpenedWinDialoag = false;

                if (result == true)
                {
                    if (!_isOpenedProject)
                    {
                        WindowLoading.ShowWindow(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_NewProject_Flowchart"), this);//显示loading窗体
                        if (wfLanguage == StaticResource.WorkflowLanguage_vb)
                        {
                            GlobalActionHandler.ProjectCreate?.Invoke(new TagEventArgs<string, string, string, string, string>(path, descri, platform, wfLanguage, StaticResource.XamlFileTemplateFlowchart_vb));
                        }
                        else if (wfLanguage == StaticResource.WorkflowLanguage_cs)
                        {
                            GlobalActionHandler.ProjectCreate?.Invoke(new TagEventArgs<string, string, string, string, string>(path, descri, platform, wfLanguage, StaticResource.XamlFileTemplateFlowchart_cs));
                        }
                        WindowLoading.CloseWindow();//关闭loading窗体
                    }
                    else
                    {
                        var cea = new CancelEventArgs();
                        GlobalActionHandler.ProjectPreclose?.Invoke(cea);
                        if (cea.Cancel)
                        {
                            return;
                        }

                        WindowLoading.ShowWindow(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_CloseProject"), this);//显示loading窗体

                        GlobalActionHandler.ProjectClosing?.Invoke(EventArgs.Empty);
                        ProjectManager.Instance.UnloadProject();

                        WindowLoading.SetContent(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_CloseProject"));
                        var loaderHost = RemoteLoaderHost.GetCurrentInstance();
                        if (loaderHost != null)
                        {
                            loaderHost.Unload(); //卸载控件程序域
                        }

                        Task.Factory.StartNew(() =>
                        {
                            System.Threading.Thread.Sleep(1000);
                            Dispatcher.Invoke(() =>
                            {
                                WindowLoading.SetContent(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_NewProject_Flowchart"));//显示loading窗体
                                try
                                {
                                    if (wfLanguage == StaticResource.WorkflowLanguage_vb)
                                    {
                                        GlobalActionHandler.ProjectCreate?.Invoke(new TagEventArgs<string, string, string, string, string>(path, descri, platform, wfLanguage, StaticResource.XamlFileTemplateFlowchart_vb));
                                    }
                                    else if (wfLanguage == StaticResource.WorkflowLanguage_cs)
                                    {
                                        GlobalActionHandler.ProjectCreate?.Invoke(new TagEventArgs<string, string, string, string, string>(path, descri, platform, wfLanguage, StaticResource.XamlFileTemplateFlowchart_cs));
                                    }
                                    WindowLoading.CloseWindow();//关闭loading窗体
                                }
                                catch (Exception ex)
                                {
                                    WindowLoading.CloseWindow();//关闭loading窗体
                                    LogHelper.Error(ex);
                                    var msgProperties = new WpfMessageBoxProperties()
                                    {
                                        Button = MessageBoxButton.OK,
                                        ButtonOkText = LocalizationProvider.GetLocalizedString("MessageBox_Button_OK"),
                                        Image = MessageBoxImage.Error,
                                        Text = LocalizationProvider.GetLocalizedString("App_MsgBox_Msg_Exception"),
                                        Title = LocalizationProvider.GetLocalizedString("App_MsgBox_Caption_Exception"),
                                    };
                                    WpfMessageBox.Show(this, ref msgProperties);
                                }
                            });
                        });
                    }
                }
            }
        }

        /// <summary>
        /// 打开工程  命令执行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmdOpenProject_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if (!_isOpenedWinDialoag)
            {
                var projectDialog = new VistaOpenFileDialog();
                projectDialog.Title = LocalizationProvider.GetLocalizedString("OpenFileDialog_Title_OpenProject");
                projectDialog.Multiselect = false;
                projectDialog.Filter = LocalizationProvider.GetLocalizedString("OpenFileDialog_Filter_OpenProject");
                _isOpenedWinDialoag = true;
                var result = projectDialog.ShowDialog(App.Current.MainWindow);
                var path = projectDialog.FileName;
                _isOpenedWinDialoag = false;

                if (result == true)
                {
                    openProject(path);
                }
            }
        }

        private void openProject(string path)
        {
            var ext = System.IO.Path.GetExtension(path);
            if (ext != StaticResource.OldProjectFile && ext != StaticResource.ProjectFile)
            {
                var msgProperties = new WpfMessageBoxProperties()
                {
                    Button = MessageBoxButton.OK,
                    ButtonOkText = LocalizationProvider.GetLocalizedString("MessageBox_Button_OK"),
                    Image = MessageBoxImage.Error,
                    Text = LocalizationProvider.GetLocalizedString("App_MsgBox_Msg_FileNotFound"),//WinMain_MsgBox_Msg_ProjectFileTypeError
                    Title = LocalizationProvider.GetLocalizedString("App_MsgBox_Cap tion_Exception"),
                };
                Window owner = Window.GetWindow(this);
                WpfMessageBox.Show(owner, ref msgProperties);
                return;
            }
            if (!_isOpenedProject) //未有打开工程
            {
                WindowLoading.ShowWindow(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_LoadProject"), this);//显示loading窗体
                GlobalActionHandler.ProjectOpen?.Invoke(new TagEventArgs<string>(path));
                WindowLoading.CloseWindow();//关闭loading窗体
            }
            else//已经存在打开的工程
            {
                var cea = new CancelEventArgs();
                GlobalActionHandler.ProjectPreclose?.Invoke(cea);
                if (cea.Cancel)
                {
                    return;
                }

                WindowLoading.ShowWindow(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_CloseProject"), this);//显示loading窗体

                GlobalActionHandler.ProjectClosing?.Invoke(EventArgs.Empty);
                ProjectManager.Instance.UnloadProject();

                WindowLoading.SetContent(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_CloseProject"));
                var loaderHost = RemoteLoaderHost.GetCurrentInstance();
                if (loaderHost != null)
                {
                    loaderHost.Unload(); //卸载控件程序域
                }

                Task.Factory.StartNew(() =>
                 {
                     System.Threading.Thread.Sleep(1000);
                     Dispatcher.Invoke(() =>
                     {
                         WindowLoading.SetContent(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_LoadProject"));//显示loading窗体
                         try
                         {
                             GlobalActionHandler.ProjectOpen?.Invoke(new TagEventArgs<string>(path));
                             WindowLoading.CloseWindow();//关闭loading窗体
                         }
                         catch (Exception ex)
                         {
                             WindowLoading.CloseWindow();//关闭loading窗体
                             LogHelper.Error(ex);
                             var msgProperties = new WpfMessageBoxProperties()
                             {
                                 Button = MessageBoxButton.OK,
                                 ButtonOkText = LocalizationProvider.GetLocalizedString("MessageBox_Button_OK"),
                                 Image = MessageBoxImage.Error,
                                 Text = LocalizationProvider.GetLocalizedString("App_MsgBox_Msg_Exception"),
                                 Title = LocalizationProvider.GetLocalizedString("App_MsgBox_Caption_Exception"),
                             };
                             WpfMessageBox.Show(this, ref msgProperties);
                         }
                     });
                 });
            }
        }

        /// <summary>
        /// 关闭工程 命令执行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmdCloseProject_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if (_isOpenedProject)
            {
                var cea = new CancelEventArgs();
                GlobalActionHandler.ProjectPreclose?.Invoke(cea);
                if (cea.Cancel)
                {
                    return;
                }

                WindowLoading.ShowWindow(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_CloseProject"), this);//显示loading窗体

                GlobalActionHandler.ProjectClosing?.Invoke(EventArgs.Empty);
                ProjectManager.Instance.UnloadProject();

                WindowLoading.SetContent(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_CloseProject"));
                var loaderHost = RemoteLoaderHost.GetCurrentInstance();
                if (loaderHost != null)
                {
                    loaderHost.Unload(); //卸载控件程序域
                }
                WindowLoading.CloseWindow();//关闭loading窗体
            }
        }

        /// <summary>
        /// 运行脚本 命令执行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmdScriptRun_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if (_isOpenedProject)
            {
                Custom.GlobalActionHandler.ScriptRun?.Invoke(EventArgs.Empty);
            }
        }

        /// <summary>
        /// 停止运行脚本 命令执行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmdScriptStop_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if (_isOpenedProject)
            {
                Custom.GlobalActionHandler.ScriptStop?.Invoke(EventArgs.Empty);
            }
        }
        /// <summary>
        /// 打开日志
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmdLogFile_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var path = System.IO.Path.Combine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase, StaticResource.Logs);
            if (FileHelper.CheckFolderExisting(path))
            {
                System.Diagnostics.Process.Start("Explorer.exe", path);
            }
        }
        /// <summary>
        /// 校验脚本
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmdValidateScript_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if (_isOpenedProject)
            {
                Custom.GlobalActionHandler.ValidateScript?.Invoke(new TagEventArgs<string>(null));
            }
        }

        /// <summary>
        /// 保存脚本 命令执行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmdScriptSave_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if (_isOpenedProject)
            {
                Custom.GlobalActionHandler.ScriptSave?.Invoke(EventArgs.Empty);
            }
        }

        /// <summary>
        /// 保存全部脚本 命令执行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmdAllScriptSave_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if (_isOpenedProject)
            {
                Custom.GlobalActionHandler.AllScriptSave?.Invoke(EventArgs.Empty);
            }
        }

        /// <summary>
        /// 发布流程  命令执行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmdProjectPublish_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if (_isOpenedProject)
            {
                Custom.GlobalActionHandler.ProjectDeploy?.Invoke(EventArgs.Empty);
            }
        }

        #region 面板切换
        /// <summary>
        /// 打开关闭工程面板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmdSwitchProjectPanel_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if (_isOpenedProject)
            {
                Custom.GlobalActionHandler.SwitchProjectPanel?.Invoke(EventArgs.Empty);
            }
        }
        /// <summary>
        /// 打开关闭活动面板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmdSwitchActivityPanel_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if (_isOpenedProject)
            {
                Custom.GlobalActionHandler.SwitchActivityPanel?.Invoke(EventArgs.Empty);
            }
        }
        /// <summary>
        /// 打开关闭片段面板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmdSwitchSnippetPanel_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if (_isOpenedProject)
            {
                Custom.GlobalActionHandler.SwitchSnippetPanel?.Invoke(EventArgs.Empty);
            }
        }
        /// <summary>
        /// 打开关闭属性面板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmdSwitchAttributePanel_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if (_isOpenedProject)
            {
                Custom.GlobalActionHandler.SwitchAttributePanel?.Invoke(EventArgs.Empty);
            }
        }
        /// <summary>
        /// 打开关闭大纲面板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmdSwitchOutlinePanel_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if (_isOpenedProject)
            {
                Custom.GlobalActionHandler.SwitchOutlinePanel?.Invoke(EventArgs.Empty);
            }
        }
        /// <summary>
        /// 打开日志面板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmdLogPanel_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if (_isOpenedProject)
            {
                Custom.GlobalActionHandler.SwitchLogPanel?.Invoke(EventArgs.Empty);
            }
        }
        #endregion

        /// <summary>
        /// 活动包设置  命令执行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmdPackageManagement_Executed(object sender, RoutedEventArgs e)
        {
            if (_isOpenedProject)
            {
                WindowPackageManagement managementWindow = new WindowPackageManagement();
                managementWindow.Owner = this;
                managementWindow.ShowDialog();
            }
        }

        private void CmdAppClose_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            this._appService.Close();
        }

        private void CmdAppSetting_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            WindowSetting appSetting = new WindowSetting();
            appSetting.Owner = this;
            appSetting.ShowDialog();
        }

        private void CmdAppAbout_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            WindowAbout windowAbout = new WindowAbout();
            windowAbout.Owner = this;
            windowAbout.ShowDialog();
        }

        private void CmdAppLicense_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            WindowLicense windowLicense = new WindowLicense();
            windowLicense.Owner = this;
            windowLicense.ShowDialog();
        }

        private void CmdAppUpgrade_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            WindowUpgrade windowUpgrade = new WindowUpgrade();
            windowUpgrade.Owner = this;
            windowUpgrade.ShowDialog();
        }
        private void CmdOpenProjectProperty_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var propertyWindow = new WindowProjectProperties();
            propertyWindow.Owner = App.Current.MainWindow;
            propertyWindow.ShowDialog();
        }

        private void CmdOpenProjectParams_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var paramsWindow = new WindowProjectParams();
            paramsWindow.Owner = App.Current.MainWindow;
            paramsWindow.ShowDialog();
        }
        private void CmdAppCut_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            GlobalActionHandler.Cut?.Invoke(EventArgs.Empty);
        }

        private void CmdAppCopy_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            GlobalActionHandler.Copy?.Invoke(EventArgs.Empty);
        }

        private void CmdAppPaste_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            GlobalActionHandler.Paste?.Invoke(EventArgs.Empty);
        }

        private void CmdAppUndo_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            GlobalActionHandler.Undo?.Invoke(EventArgs.Empty);
        }

        private void CmdAppRedo_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            GlobalActionHandler.Redo?.Invoke(EventArgs.Empty);
        }

        private void CmdAppFind_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if (_isOpenedProject)
            {
                Custom.GlobalActionHandler.AllScriptSave?.Invoke(EventArgs.Empty);
            }
            GlobalActionHandler.Find?.Invoke(EventArgs.Empty);
        }

        private void CmdAppReplace_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            GlobalActionHandler.Replace?.Invoke(EventArgs.Empty);
        }
        private void CmdNotesActivity_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            GlobalActionHandler.Notes?.Invoke(EventArgs.Empty);
        }
        private void CmdCancelNotesActivity_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            GlobalActionHandler.CancelNotes?.Invoke(EventArgs.Empty);
        }

        /// <summary>
        /// 帮助文档 命令执行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmdHelpDocumnet_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var path = System.IO.Path.Combine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase, StaticResource.HelpDocumnet);
            System.Diagnostics.Process.Start("Explorer.exe", path);
        }
        #endregion

        #region 调试 

        private void CmdToggleBreakPoint_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            GlobalActionHandler.BreakPointToggle?.Invoke(EventArgs.Empty);
        }

        private void CmdScriptDebug_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            GlobalActionHandler.ScriptDebug?.Invoke(EventArgs.Empty);
        }

        private void CmdScriptDebugByStep_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            GlobalActionHandler.ScriptDebugByStep?.Invoke(EventArgs.Empty);
        }

        #endregion

        private void ToolBar_Loaded(object sender, RoutedEventArgs e)
        {
            ToolBar toolBar = sender as ToolBar;
            var overflowGrid = toolBar.Template.FindName("OverflowGrid", toolBar) as FrameworkElement;
            if (overflowGrid != null)
            {
                overflowGrid.Visibility = Visibility.Collapsed;
            }
        }

        private void Window_Closing(object sender, CancelEventArgs cea)
        {
            if (_isOpenedProject)
            {
                GlobalActionHandler.ProjectPreclose?.Invoke(cea);
                if (cea.Cancel)
                {
                    return;
                }

                GlobalActionHandler.ProjectClosing?.Invoke(EventArgs.Empty);
                ProjectManager.Instance.UnloadProject();
            }
        }
        private async Task<bool> isUpgrade()
        {
            var currentVer = new Version(AssemblyInfoHelper.AssemblyVersion);

            try
            {
                _lastestVersion = await _sysUpgradeService.GetLastestVersionAsync();
            }
            catch (Exception ex)
            {
                DWF.Studio.Share.Log.LogHelper.Error(ex);
                return false;
            }

            if (_lastestVersion != null)
            {
                var lastVer = new Version(_lastestVersion.Version);

                if (lastVer > currentVer)
                {
                    return true;
                }
            }
            return false;
        }
    }
}
